// packageB/member/income/regional-agent/apply/apply.js
const app = getApp()
import WxValidate from '../../../../../utils/WxValidate.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      real_name: '',
      mobile: '',
      region: '',
      regionText: ''
    },
    // 地区数据
    areaList: {},
    chooseRegionShow: false,
    streetText: '',
    chooseStreetShow: false,
    streetColumns: [],
    memberInfo: {},
    // 当前选中地区规则，如果没有则使用对应地区公共规则
    applyRule: {},
    // 公共规则，包含province、city、district、street
    publicRule: {},
    // 本地区实际完成任务数
    areaTaskNum: 0,
    taskNumber: 0,
    // 当前用户实际直推符合条件的人数
    recommendedNum: 0,
    // 本地区是否存在代理，0-无，1-有
    hasAgent: 0,
    loading: false
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 显示区域选择弹窗
   */
  showRegion: function() {
    // const { area } = this.data.memberInfo
    // if (area.length) return
    this.setData({
      chooseRegionShow: true
    })
  },

  /**
   * 地区选中确认
   * @param {Object} e 
   */
  areaConfirm: function(e) {
    const { values } = e.detail
    if (!values[0].code) {
      app.tips('请选择地区')
      return
    }
    const areaTextList = []
    values.forEach(item => {
      if (item && item.name) {
        areaTextList.push(item.name)
      }
    })
    this.setData({
      'formData.region': {
        province: values[0].code,
        city: values[1] && values[1].code ? values[1].code : '',
        district: values[2] && values[2].code ? values[2].code : '',
        street: ''
      },
      streetText: '',
      'formData.regionText': areaTextList.join('/'),
      chooseRegionShow: false
    })
    this.getAgencyRule()
    if(values[2] && values[2].code && !this.memberInfo?.area?.length) {
      this.getStreetList(values[2].code)
    }
  },

  /**
   * 通过县级id获取街道数据
   * @param {String | Number} district_id 县级id
   */
  getStreetList: function(district_id) {
    if(!district_id) return
    this.setData({ streetColumns: [] })
    wx.showLoading({ title: '获取街道...' })
    const _this = this
    app._getNetWork({
      url: app.getNetAddresss('member.memberAddress.street'),
      data: { district_id },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ streetColumns: resData.data || [] })
        } else {
          app.tips(resData.msg || '街道数据获取失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 街道选中
   * @param {Object} e 
   */
  streetConfirm: function(e) {
    const { value } = e.detail
    this.setData({
      'formData.region.street': value.id,
      streetText: value.areaname,
      chooseStreetShow: false
    })
    this.getAgencyRule()
  },

  /**
   * 查询申请规则
   */
  getAgencyRule: function() {
    const { formData, publicRule } = this.data
    const { region } = formData
    wx.showLoading({ title: '规则查询...' })
    const _this = this
    app._getNetWork({
      url: app.getNetAddresss('plugin.area-dividend.api.area-dividend.getAgencyRule'),
      data: region,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { hasAlone, aloneRule, areaTaskNum, recommendedNum, hasAgent, taskNumber } = resData.data
          _this.setData({ areaTaskNum, recommendedNum, hasAgent, taskNumber })
          if (hasAlone) {
            // 如果存在独立规则使用当前地区规则
            _this.setData({
              applyRule: aloneRule
            })
          } else {
            // 不存在独立规则使用公共规则
            if (region.street) {
              // 街道公共规则
              _this.setData({
                applyRule: publicRule.street
              })
            } else if(region.district) {
              // 县级公共规则
              _this.setData({
                applyRule: publicRule.district
              })
            } else if(region.city) {
              // 市级公共规则
              _this.setData({
                applyRule: publicRule.city
              })
            } else if(region.province) {
              // 省级公共规则
              _this.setData({
                applyRule: publicRule.province
              })
            }
          }
        } else {
          app.tips(resData.msg || '规则查询失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 初始化表单验证
   */
  initValidate: function() {
    const rules = {
      real_name: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      }
    }
    const message = {
      real_name: {
        required: '请输入姓名'
      },
      mobile: {
        required: '请输入手机号码',
        tel: '请输入正确的手机号码'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
  },

  /**
   * 提交
   */
  submit: function() {
    const { formData, memberInfo, applyRule, areaTaskNum, recommendedNum, hasAgent, taskNumber } = this.data
    const { area, level_id } = memberInfo
    const { real_name, mobile, region } = formData
    const { province, city, district, street } = region
    const { tasknum, people, memberlevel, memberlevelname, areanumber } = applyRule
    if (area.length == 1) {
      app.tips('已是最高级别代理！')
      return
    }
    if (!this.WxValidate.checkForm(formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    if (!province) {
      app.tips('请选择地区！')
      return
    }
    if (hasAgent) {
      app.tips('该地区已存在代理！')
      return
    }
    if (areaTaskNum < areanumber) {
      app.tips(`地区任务数要达到${areanumber}人以上`)
      return
    }
    if (taskNumber < tasknum) {
      app.tips(`个人任务数要达到${tasknum}人以上`)
      return
    }
    if (recommendedNum < people) {
      app.tips(`直推${memberlevelname}要达到${people}人以上`)
      return
    }
    if (level_id < memberlevel) {
      app.tips(`需要【${memberlevelname}】及以上会员身份`)
      return
    }
    const urlStr = area.length ? "plugin.area-dividend.api.area-dividend.apply-again" : "plugin.area-dividend.api.area-dividend.set-agent-apply"
    const json = {
      real_name,
      mobile,
      province_id: province,
      city_id: city,
      district_id: district,
      street_id: street
    }
    const data = { data: JSON.stringify(json) }
    const _this = this
    this.setData({ loading: true })
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          app.tips('提交成功！')
          setTimeout(() => {
            wx.redirectTo({
              url: '/packageG/member_v2/member_v2',
            })
          }, 1500)
        } else {
          app.tips(resData.msg || '提交失败！')
        }
      },
      complete: function() {
        _this.setData({ loading: false })
      }
    })
  },

  /**
   * 通过value查找key
   * @param {Object} obj 目标对象
   * @param {String} value 值
   * @returns {String | Number | null} key
   */
  findKeyByValue: function(obj, value) {
    const keyValuePair = Object.entries(obj).find(pair => pair[1] === value);
    return keyValuePair ? keyValuePair[0] : null;
  },

  /**
   * 初始化地区
   */
  initRegion: function() {
    const { memberInfo, areaList, publicRule } = this.data
    const { area } = memberInfo
    // 已经是代理且不是升级代理
    if (area.length && area.length > 1) {
      // 地区显示文字
      this.setData({
        'formData.regionText': area.slice(0, area.length - 1).join('/')
      })
      const { province_list, city_list, county_list } = areaList
      let province_id = '', city_id = '', district_id = ''
      // 省级id
      province_id = this.findKeyByValue(province_list, area[0])
      // 当前代理区域县级及以下
      if (area.length > 2) {
        // 市级id
        city_id = this.findKeyByValue(city_list, area[1])
      }
      // 当前代理区域县级以下
      if (area.length > 3) {
        // 县级id
        district_id = this.findKeyByValue(county_list, area[2])
      }
      this.setData({
        'formData.region': {
          province: province_id,
          city: city_id,
          district: district_id,
          street: ''
        }
      })
      this.getAgencyRule()
    }
  },

  /**
   * 初始化地区数据
   */
  _initAddressInfo: function() {
    const _this = this
    wx.showLoading({ title: '初始化地区...' })
    app._getNetWork({
      url: app.getNetAddresss("member.member-address.address"),
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const areaList = {
            province_list: {},
            city_list: {},
            county_list: {}
          }
          resData.data.province.forEach(item => {
            areaList.province_list[item.id] = item.areaname
          })
          resData.data.city.forEach(item => {
            areaList.city_list[item.id] = item.areaname
          })
          resData.data.district.forEach(item => {
            areaList.county_list[item.id] = item.areaname
          })
          _this.setData({
            areaList
          })
          _this.initRegion()
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 获取用户信息及公共规则
   */
  getMemberInfo: function() {
    const _this = this
    wx.showLoading({
      title: '获取用户信息...',
    })
    app._getNetWork({
      url: app.getNetAddresss('plugin.area-dividend.api.area-dividend.getMemberInfo'),
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const _data = resData.data
          _this.setData({ 
            memberInfo: _data,
            publicRule: _data.publicRule
          })
          // _this.setData({
          //   'memberInfo.area': ['河北省', '唐山市', '路南区', '友谊街道']
          // })
          _this._initAddressInfo()
        } else {
          app.tips(resData.msg || '用户信息获取失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate()
    this.getMemberInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})